package com.changgou.system.filter;

import com.changgou.system.util.JwtUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 鉴权过滤器
 */
@Component
public class AuthorizeFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取请求对象
        ServerHttpRequest request = exchange.getRequest();
        //获取响应对象
        ServerHttpResponse response = exchange.getResponse();
        //判断当前请求是否是登录请求,如果是就放行
        //获取客户端请求路径
        String path = request.getURI().getPath();
        if(path.contains("/admin/login")){
            return chain.filter(exchange);
        }
        //获取请求头信息
        HttpHeaders headers = request.getHeaders();
        //获取token信息
        String token = headers.getFirst("token");
        if(StringUtils.isEmpty(token)){
            //如果为null就返回错误提示信息:认证失败
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        //基于jwtutil工具类进行令牌解析
        try {
            //令牌解析成功
            JwtUtil.parseJWT(token);
        } catch (Exception e) {
            e.printStackTrace();
            //如果解析失败就返回错误提示信息:认证失败
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
